const fs = require("fs");
// Remove unused path import
// const path = require('path');
const { generateWordASSStyles } = require("./wordAssStyles");
const { parseASSWithDurations } = require("./assParser");
const { getWordsForSubtitle } = require("./wordProcessor");
const { loadConfig } = require("./config");
const config = loadConfig();
/**
 * 生成单词ASS字幕内容
 * @param {Array} subtitles - 字幕条目数组
 * @param {object} wordStyles - 单词样式配置
 * @returns {string} ASS字幕内容
 */
async function generateWordASSContent(subtitles, wordStyles) {
  // 生成ASS头部
  let assContent = `[Script Info]
Title: Word Subtitles
ScriptType: v4.00+
WrapStyle: 0
ScaledBorderAndShadow: yes
YCbCr Matrix: TV.601
PlayResX: ${config.projectSettings.videoWidth}
PlayResY: ${config.projectSettings.videoHeight}

`;

  // 生成样式部分
  assContent += generateWordASSStyles(wordStyles);
  // 生成事件部分头部
  assContent += `
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
`;

  let MarginV = 0;
  if (subtitles.length === 1) {
    MarginV = 180;
  } else if (subtitles.length === 2) {
    MarginV = 120;
  } else if (subtitles.length === 3) {
    MarginV = 60;
  }
  let existWords = [];
  const lineHeight = Math.max(wordStyles.word.fontSize, wordStyles.phonetic.fontSize) + wordStyles.translation.fontSize;
  // 处理每个字幕条目
  for (const [index, subtitle] of subtitles.entries()) {
    try {
      // 获取单词信息
      if (!subtitle) continue;
      let maxNumber = undefined;
      if (process.env.wordType === "nomoveeffect") {
        maxNumber = 3;
      }
      const words = await getWordsForSubtitle(subtitle.text, maxNumber);

      // 如果没有单词，跳过处理
      if (words.length === 0) continue;

      // 保持所有单词在同一时间段显示
      const wordStart = subtitle.startTime;
      const wordEnd = subtitle.endTime;

      // 计算字幕时间段的总时长(秒)
      // 为每个单词生成独立的字幕条目，以恢复换行效果
      words.forEach((word, wordIndex) => {
        // console.log(" word: ", index, word.word)
        if (existWords.indexOf(word.word) > -1) {
          word.word = "";
          word.trans = "";
          word.pronounce = "";
        } else existWords.push(word.word);

        // 计算每个单词的动画延迟时间（毫秒）
        // 让每个单词的动画有明显的时间间隔
        let delay = wordIndex * 200; // 每个单词间隔200毫秒开始动画
        let animationDuration = 400; // 动画持续400毫秒

        // 生成带飞入动画的字幕文本
        // 调整初始位置更靠近屏幕，避免距离左侧太远
        const height = wordIndex * lineHeight + 100;
        let wordText = "";
        if (process.env.wordType === "nomoveeffect") {
          wordText = `{\\rWord}${word.word}`;
        } else {
          wordText = `{\\move(${config.projectSettings.videoWidth},${height},100,${height},${delay},${delay + animationDuration})}{\\rWord}${word.word}`;
        }
        if (word.pronounce) {
          wordText += ` {\\rPhonetic}{\\i1}${word.pronounce}{\\i0}{\\rWord}`;
        }
        if (word.trans) {
          let translation = word.trans;
          if (translation.length > 40) {
            translation = translation.substring(0, 28) + "...";
          }
          wordText += `\\N{\\rTranslation}${translation}`;
        }

        // 每个单词独立一行显示，恢复原有的换行效果
        if (process.env.wordType === "nomoveeffect") {
          assContent += `Dialogue: 0,${wordStart},${wordEnd},Word,,0,0,${MarginV},,${wordText}\n`;
        } else {
          assContent += `Dialogue: 0,${wordStart},${wordEnd},Word,,0,0,0,,${wordText}\n`;
        }
      });
    } catch (error) {
      console.error(`！！！处理字幕条目时出错 (索引: ${index}):`, error.message);
    }
  }

  return assContent;
}

/**
 * 从ASS文件生成单词字幕文件
 * @param {string} assPath - 输入ASS文件路径
 * @param {string} wordAssPath - 输出单词ASS文件路径
 * @param {object} wordStyles - 单词样式配置
 * @returns {boolean} 是否成功生成
 */
async function generateWordASSFromFile(assPath, wordAssPath, wordStyles) {
  try {
    console.log(`  开始生成单词字幕文件...`);
    console.log(`- 输入ASS文件: ${assPath}`);
    console.log(`- 输出单词ASS文件: ${wordAssPath}`);

    // 解析ASS文件获取字幕条目
    const subtitles = parseASSWithDurations(assPath);
    console.log(`- 解析到 ${subtitles.length} 个字幕条目`);

    // 生成单词ASS内容
    const assContent = await generateWordASSContent(subtitles, wordStyles);

    // 统计信息
    let processedSubtitles = 0;
    let totalWords = 0;
    // Remove unused variable
    // let failedSubtitles = 0;

    // 处理每个字幕条目
    for (const subtitle of subtitles) {
      try {
        processedSubtitles++;
        const words = await getWordsForSubtitle(subtitle.text);
        totalWords += words.length;
      } catch (error) {
        // failedSubtitles++;
        console.error("！！！处理字幕条目时出错:", error.message);
        console.error("！！！错误详情:", error);
        // 即使某个条目出错也继续处理其他条目
      }
    }

    console.log(`- 处理了 ${processedSubtitles} 个字幕条目`);
    console.log(`- 总共找到 ${totalWords} 个单词`);

    // 写入文件，使用UTF-8编码
    fs.writeFileSync(wordAssPath, assContent, "utf-8");
    console.log(`  单词字幕文件已生成: ${wordAssPath}`);
    return true;
  } catch (error) {
    console.error("！！！  ■生成单词ASS文件时出错:", error);
    return false;
  }
}

module.exports = {
  generateWordASSContent,
  generateWordASSFromFile,
};
